package dhm.com.hpx.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.ExportAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.ExportCustomerBean;
import dhm.com.hpx.entity.ExportListBean;
import dhm.com.hpx.entity.ProjectBean;
import dhm.com.hpx.utils.ExcelUtils;
import dhm.com.hpx.utils.SpUtils;

public class ExportActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.recy)
    XRecyclerView recy;

    private PressenterImpl pressenter;
    private String uid;
    private int page=1;
    private ExportAdapter adapter;
    private List<ExportListBean.DataBean> beanList;



    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private int REQUEST_PERMISSION_CODE = 1000;


    private String filePath = "/sdcard/AndroidExcelDemo";


    @Override
    protected int getLayout() {
        return R.layout.activity_export;
    }



    private ProgressDialog progDialog = null;// 搜索时进度条

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter=new PressenterImpl();
        pressenter.attachView(this);

        uid = SpUtils.getString(this, "uid");
        page=1;

        LinearLayoutManager manager=new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        recy.setLoadingMoreEnabled(true);
        recy.setPullRefreshEnabled(true);
        recy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page=1;
                getdata();
            }

            @Override
            public void onLoadMore() {
                getdata();
            }
        });




        adapter = new ExportAdapter(this);
        adapter.setdeleteClick(new ExportAdapter.OnClick() {
            @Override
            public void item(int posttion) {
                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("export_id",beanList.get(posttion).getExport_id()+"");
                pressenter.sendMessage(ExportActivity.this,Constant.export_log_customer,map, ExportCustomerBean.class);
            }
        });

        recy.setAdapter(adapter);
        getdata();
    }

    private void getdata() {
        Map<String,String> map=new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid",uid);
        map.put("page",page+"");
        pressenter.sendMessage(this,Constant.export_log,map, ExportListBean.class);

    }

    @Override
    protected void initData() {

    }

    @Override
    public void requesta(Object data) {
        if (data instanceof ExportListBean){
            ExportListBean exportListBean= (ExportListBean) data;
            if (exportListBean.getCode()==1){
                if (page==1){
                    beanList = exportListBean.getData();
                }else {
                    beanList.addAll(exportListBean.getData());
                }
                adapter.setList(beanList);
                page++;

            }
            recy.refreshComplete();
            recy.loadMoreComplete();
        }else if (data instanceof ExportCustomerBean){
            ExportCustomerBean exportCustomerBean= (ExportCustomerBean) data;
            if (exportCustomerBean.getCode()==1){
                if (Build.VERSION.SDK_INT > 23) {
                    if (ContextCompat.checkSelfPermission(this, permissions[0])
                            == PackageManager.PERMISSION_GRANTED) {
                        //授予权限
                        showProgressDialog();
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String excelFileName = "/demo.xls";
                        String[] title = {"公司名称", "联系方式", "地址"};
                        String sheetName = "demoSheetName";
                        List<ProjectBean> demoBeanList = new ArrayList<>();
                        for (int i = 0; i < exportCustomerBean.getData().size(); i++) {
                                ProjectBean projectBean = new ProjectBean();
                                projectBean.setName(exportCustomerBean.getData().get(i).getCompany_name());
                                projectBean.setPhone(exportCustomerBean.getData().get(i).getTel());
                                projectBean.setAddress(exportCustomerBean.getData().get(i).getAddress());
                                demoBeanList.add(projectBean);

                        }
                        if (demoBeanList == null || demoBeanList.size() == 0) {
                            Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                            dissmissProgressDialog();
                            return;
                        }
                        filePath = filePath + excelFileName;
                        ExcelUtils.initExcel(filePath, sheetName, title);
                        ExcelUtils.writeObjListToExcel(demoBeanList, filePath, this);
                        dissmissProgressDialog();
                        Toast.makeText(this, "excel已导出至：" + filePath, Toast.LENGTH_SHORT).show();
                    } else {
                        //未获得权限
                        requestPermissions(permissions, REQUEST_PERMISSION_CODE);
                    }
                } else {
                    showProgressDialog();
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String excelFileName = "/demo.xls";
                    String[] title = {"公司名称", "联系方式", "地址"};
                    String sheetName = "demoSheetName";
                    List<ProjectBean> demoBeanList = new ArrayList<>();
                    for (int i = 0; i < exportCustomerBean.getData().size(); i++) {
                            ProjectBean projectBean = new ProjectBean();
                            projectBean.setName(exportCustomerBean.getData().get(i).getCompany_name());
                            projectBean.setPhone(exportCustomerBean.getData().get(i).getTel());
                            projectBean.setAddress(exportCustomerBean.getData().get(i).getAddress());
                            demoBeanList.add(projectBean);
                    }
                    if (demoBeanList == null || demoBeanList.size() == 0) {
                        Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                        dissmissProgressDialog();
                        return;
                    }
                    filePath = filePath + excelFileName;
                    ExcelUtils.initExcel(filePath, sheetName, title);
                    ExcelUtils.writeObjListToExcel(demoBeanList, filePath, this);
                    dissmissProgressDialog();
                    Toast.makeText(this, "excel已导出至：" + filePath, Toast.LENGTH_SHORT).show();
                }
            }

        }

    }

    @Override
    public void fail(String error) {

    }

    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }


    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null) {
            progDialog = new ProgressDialog(this);
        }
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索...");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }



}
